from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import HttpResponse
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework.generics import GenericAPIView
from . import serializers
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.get


# 发送短信验证码
# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    """发送短信验证码"""
    # 指定序列化器
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        # DRF实现参数的校验和图片验证码的校验

        # 获取序列化期器对象：
        serializer = self.get_serializer(data = request.query_params)
        # 开启校验
        serializer.is_valid(raise_exception = True)

        # 生成短信验证码
        print(mobile)
        sms_code = '%06d' % random.randint(0,999999)
        print(sms_code)
        # # 将短信验证码信息保存到redis数据库中
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # # 记录发送短信的标记
        # redis_conn.setex('send_flag_%s' % mobile, constants.SMS_CODE_REDIS_INTERVAL, 1)

        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 记录发送短信的标记
        pl.setex('send_flag_%s' % mobile, constants.SMS_CODE_REDIS_INTERVAL, 1)
        pl.execute()

        # 发送短信验证码(手机号，[验证码,存在时间],发送模板id)
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SMS_SEND_TEMPLATE_ID)

        # 执行异步任务:delay将延迟异步任务发送到redis
        send_sms_code.delay(mobile, sms_code)

        # 返回数据
        return Response({"message":"ok"})


# 生成图片验证码
# url('^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()),
class ImageCodeView(APIView):
    """提供图片验证码"""

    def get(self,request, image_code_id):
        # print(image_code_id)
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 保存图片验证码内容
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex('image_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # except Exception as e:
        #     print('==============',e)
        # 响应图片数据
        return HttpResponse(image,content_type='image/jpg')
